<?php
namespace app\admin\controller;

use think\Controller;
use think\Request;
use think\captcha\Captcha;
use app\admin\model\AdminRole;
use Db;
use think\facade\Session;
use think\facade\Log;

class Index extends Controller
{ 
    // protected $middleware = [
    //     'Before'=> ['except' 	=> ['login','dologin','getLog'] ],
    // ];
    //后台首页左侧边栏
    public function index()
    {
        return $this->fetch('index');
    }
    //后台首页右
    public function welcome()
    {
        return $this->fetch('welcome');
    }
    //登录界面
    public function login()
    {
        return $this->fetch('login');
    }
    //登录验证
    public function dologin(Request $req)
    {   
        $data = $req->param();
        
        // $captcha = new Captcha();

        // if( !$captcha->check($data['code']))
        // {
        //     return $this->error('验证码错误');
        // }
        $validate = new \app\admin\validate\Index;

        $data = [
            '__token__' => $data['__token__'],
            'user_name' => $data['user_name'],
            'password'  => $data['password']
        ];

        if (!$validate->check($data)) {
         $this->error($validate->getError());
        }

        $num = Db::table('admin')->where('username',$data['user_name'])->where('password',md5($data['password']))->find();

        if($num==NULL){
            Log::write('账号不存在'.$data['user_name'].'或者密码错误'.$data['password'],'error');

            return $this->error('该账号不存在');
           
        }else{
            // var_dump($num);die;
            Session::set('admin_name',$num['username']);
            Session::set('admin_id',$num['id']);

            $url_path = AdminRole::alias('a')->field('c.url_path')->join('role_privilege b','a.role_id=b.role_id')->join('privilege c','b.pri_id=c.id')->where('a.admin_id',$num['id'])->select();
            foreach ($url_path as $v){
                $path[] = $v->toArray();
            }

            if($num['username']=='root'){
                Session::set('path','root');
            }else{
                Session::set('path',$path);
            }

            Log::write($num['username'].'登陆成功','info');

            return redirect('/admin/index/index');
        }

    }
    //验证码生成
    public function verify()
    {
        $captcha = new Captcha();
        return $captcha->entry();    
    }

    //获取日志
    public function getLog()
    {   

        Log::write('你是不是做错了什么','error');



        $logs = Log::getLog();
        echo '<pre>';
        var_dump($logs);
    }

}



?>